package auth.service.impl;

import auth.mapper.AdminMapper;
import auth.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import common.dto.coupon.UserCouponDTO;
import auth.service.CouponServiceFeignClient;
import auth.service.FavoriteServiceFeignClient;
import auth.service.IUserService;
import auth.service.OrderServiceFeignClient;
import common.model.user.User;
import common.dto.coupon.CouponDTO;
import common.dto.orderdto.OrderDTO;
import common.dto.userdto.FavoriteDTO;
import common.dto.userdto.UserDTO;
import common.dto.userdto.UserDashboard;
import common.model.result.Result;
import common.model.result.ResultCodeEnum;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Base64;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import common.model.coupon.Coupon;
import common.model.user.Favorite;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private OrderServiceFeignClient orderServiceFeignClient;

    @Autowired
    private FavoriteServiceFeignClient favoriteServiceFeignClient;

    @Autowired
    private CouponServiceFeignClient couponServiceFeignClient;

    @Autowired
    private ObjectMapper objectMapper;
    
    // 密码加密用的盐值
    private static final String PASSWORD_SALT = "web_back_secure_salt_2025";

    // 根据手机号查询用户
    @Override
    public User findByPhone(String phone) {
        return userMapper.findUserByPhone(phone);
    }
    // 创建新用户
    @Override
    public void createUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setNickName("用户" + user.getTelephone().substring(7)); // 默认昵称为"用户"+手机号后4位
        user.setIcon("/images/mihoyo.jpg");
        
        // 如果设置了密码，进行加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(encryptPassword(user.getPassword()));
        }
        
        userMapper.insertUser(user);
    }
    //更新用户信息
    @Override
    public Result updateUser(UserDTO userDTO) {        
        // 先查询用户
        User user = userMapper.findUserByPhone(userDTO.getTelephone());
        System.out.println(userDTO + "user: " + user);
        if (user == null) {
            return Result.failure(ResultCodeEnum.FAIL, "用户不存在");
        }
        
        // 更新需要修改的字段
        if (userDTO.getNickName() != null) {
            user.setNickName(userDTO.getNickName());
        }
        if (userDTO.getIcon() != null) {
            user.setIcon(userDTO.getIcon());
        }
        if (userDTO.getEmail() != null) {
            user.setEmail(userDTO.getEmail());
        }
        user.setUpdateTime(LocalDateTime.now());
        
        // 使用BaseMapper的updateById方法更新
        userMapper.updateById(user);
        
        return Result.success();
    }
    
    //修改密码
    @Override
    public void updatePassword(String password, String phone) {
        // 对密码进行加密
        String encryptedPassword = encryptPassword(password);
        userMapper.updatePassword(encryptedPassword, phone);
    }
    
    /**
     * 加密密码
     * @param plainPassword 明文密码
     * @return 加密后的密码
     */
    private String encryptPassword(String plainPassword) {
        try {
            // 使用SHA-256加密算法
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            
            // 将密码和盐值组合
            String passwordWithSalt = plainPassword + PASSWORD_SALT;
            
            // 进行加密
            byte[] hashedBytes = md.digest(passwordWithSalt.getBytes());
            
            // 转为Base64字符串
            return Base64.getEncoder().encodeToString(hashedBytes);
        } catch (NoSuchAlgorithmException e) {
            // 如果SHA-256算法不可用，回退到MD5
            System.err.println("SHA-256 不可用，使用MD5加密: " + e.getMessage());
            return DigestUtils.md5DigestAsHex((plainPassword + PASSWORD_SALT).getBytes());
        }
    }
    
    /**
     * 验证密码
     * @param plainPassword 明文密码
     * @param encryptedPassword 加密后的密码
     * @return 是否匹配
     */
    public boolean verifyPassword(String plainPassword, String encryptedPassword) {
        // 对输入的明文密码进行相同的加密
        String hashedInput = encryptPassword(plainPassword);
        
        // 比较加密后的密码是否匹配
        return hashedInput.equals(encryptedPassword);
    }

    //获取用户列表
    @Override
    public Result getUserList() {
        List<User> userList = userMapper.selectList(null);
        //将userList转为UserDTO
        List<UserDTO> userDTOList = userList.stream().map(user -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
            return userDTO;
        }).collect(Collectors.toList());
        return Result.success(userDTOList);
    }

    //获取所有用户
    @Override
    public Result getUserListForCart() {
        List<User> userList = userMapper.selectList(null);
        return Result.success(userList);
    }

    //根据id获取用户详情
    @Override
    public Result getUserDetail(Long id) {
        User user = userMapper.selectById(id);
        return Result.success(user);
    }
    //用户仪表盘
    @Override
    public Result getUserDashboard(Long uid) {
        UserDashboard userDashboard = new UserDashboard();
        
        // 获取该用户订单列表
        Result orderListResult = orderServiceFeignClient.getOrderList(uid);
        // 获取该用户收藏列表
        Result favoriteListResult = favoriteServiceFeignClient.getFavoriteList(uid);
        // 获取该用户的优惠券列表
        Result couponListResult = couponServiceFeignClient.getCouponList(uid);

        try {
            // 解包订单列表
            List<OrderDTO> orderList = objectMapper.convertValue(orderListResult.getData(), 
                new TypeReference<List<OrderDTO>>() {});
            userDashboard.setOrderLenth(orderList != null ? orderList.size() : 0);

            // 解包收藏列表
            List<FavoriteDTO> favoriteList = objectMapper.convertValue(favoriteListResult.getData(), 
                new TypeReference<List<FavoriteDTO>>() {});
            userDashboard.setFavoriteLenth(favoriteList != null ? favoriteList.size() : 0);
            
            // 获取最新三条收藏
            List<FavoriteDTO> recentFavorites = favoriteList != null ? 
                favoriteList.stream()
                    .limit(3)
                    .collect(Collectors.toList()) : 
                new ArrayList<>();
            userDashboard.setRcentFavorite(recentFavorites);

            // 解包优惠券列表
            List<UserCouponDTO> couponList = objectMapper.convertValue(couponListResult.getData(), 
                new TypeReference<List<UserCouponDTO>>() {});
            userDashboard.setCouponLenth(couponList != null ? couponList.size() : 0);
            
            // 获取最新三条优惠券
            List<UserCouponDTO> recentUserCoupons = couponList != null ? 
                couponList.stream()
                    .limit(3)
                    .collect(Collectors.toList()) : 
                new ArrayList<>();
            userDashboard.setRecentCoupon(recentUserCoupons);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure(ResultCodeEnum.FAIL, "数据转换失败");
        }

        return Result.success(userDashboard);
    }

    //更新用户信息
    @Override
    public Result jiangUpdateUser(User user) {
        userMapper.updateById(user);
        return Result.success();
    }

    //删除用户
    @Override
    public Result jiangDeleteUser(Long id) {
        userMapper.deleteById(id);
        return Result.success();
    }

    @Override
    public Result getOnlinAdminId() {
        return null;
    }
}
